package com.yiyihealth.cherriesadmin.controller;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.json.JSONObject;
import com.yiyihealth.cherriesadmin.core.http.HttpResult;
import com.yiyihealth.cherriesadmin.core.smsInterface.AliyunSmsUtil;
import com.yiyihealth.cherriesadmin.core.smsInterface.SmsUtil;
import com.yiyihealth.cherriesadmin.core.web.BaseController;
import com.yiyihealth.cherriesadmin.model.PubPatients;
import com.yiyihealth.cherriesadmin.model.PubSufferer;
import com.yiyihealth.cherriesadmin.model.wrapper.PubPatientsWrapper;
import com.yiyihealth.cherriesadmin.service.PubPatientsService;
import com.yiyihealth.cherriesadmin.service.PubSuffererService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 患者信息表(PubPatients)表控制层
 *
 * @author chen
 * @since 2020-09-14 20:03:51
 */
@Api(tags = "患者管理类")
@RestController
@RequestMapping("pubPatients")
public class PubPatientsController extends BaseController<PubPatients, PubPatientsWrapper, Long> {
    /**
     * 服务对象
     */
    @Resource
    private PubPatientsService patientsService;
    @Resource
    private PubSuffererService suffererService;

    @Override
    @InitBinder()
    public void initBinder(WebDataBinder binder) {
        super.setBaseService(patientsService);
    }

    @ApiOperation(value = "检索患者信息")
    @GetMapping("selectpatientsFuzzyquery")
    public HttpResult selectpatientsFuzzyquery(@RequestBody PubPatients patients){
        Map<String,Object> map=new HashMap<String,Object>();
        return HttpResult.success(patientsService.selectpatientsFuzzyquery(map));
    }

    @ApiOperation(value = "H5检索患者信息")
    @RequestMapping("/selectById")
    @ResponseBody
    public HttpResult selectById(@RequestParam Long id) throws Exception {
        return HttpResult.success(patientsService.selectByPrimaryKey(id));
    }

    @ApiOperation(value = "H5获取手机验证码")
    @PostMapping("/getVerificationCode")
    @ResponseBody
    public HttpResult getVerificationCode(HttpServletRequest request, @RequestParam String phone) throws Exception {
        String code  = SmsUtil.smsCode();
        JSONObject jsonObject = new JSONObject();
        jsonObject.set("code",code);
        AliyunSmsUtil.sendSms(phone,"SMS_205290017",jsonObject.toString());
        request.getSession().setAttribute("code", code);
        return HttpResult.success(code);
    }

    @ApiOperation(value = "H5账号密码登录")
    @PostMapping("/userLogin")
    @ResponseBody
    public HttpResult userLogin(@RequestParam  String account,@RequestParam String password) throws Exception {
        List<PubPatients> patientsList = new ArrayList<>();
        Map<String,Object> map = new HashMap<>(7);
        if (isPhone(account)){
            map.put("patPhone",account);
            map.put("password",password);
            patientsList=patientsService.selectList(map);
        }else {
            map.put("patName",account);
            map.put("password",password);
            patientsList=patientsService.selectList(map);
        }
        PubPatients patients=new PubPatients();
        if (!CollectionUtils.isEmpty(patientsList)){
            patients=patientsList.get(0);
        }

        return HttpResult.success(patients);
    }

    public static boolean isPhone(String phone) {
        String regex = "^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(166)|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[8|9]))\\d{8}$";
        if (phone.length() != 11) {
            return false;
        } else {
            Pattern p = Pattern.compile(regex);
            Matcher m = p.matcher(phone);
            return m.matches();
        }
    }
    @ApiOperation(value = "H5手机验证码登录")
    @PostMapping("/phoneLogin")
    @ResponseBody
    public HttpResult phoneLogin(@RequestParam String phone,@RequestParam String code,@RequestParam String codes) throws Exception {
        if (!code.equals(codes)){
            return  HttpResult.failure("验证码不正确");
        }
        PubPatients patients = new PubPatients();
        Map<String,Object> map = new HashMap<>(7);
        map.put("patPhone",phone);
        List<PubPatients> patientsList =patientsService.selectList(map);
        if (CollectionUtils.isEmpty(patientsList)){
            patients.setPassword(phone);
            patients.setPatPhone(phone);
            if (!Optional.ofNullable(patients.getPatName()).isPresent()){
                patients.setPatName(" ");
            }
            patients =  patientsService.insert(patients);
        }else {
            patients = patientsList.get(0);
        }
        return HttpResult.success(patients);
    }

    @ApiOperation(value = "H5患者信息修改")
    @RequestMapping("/modifyPatient")
    @ResponseBody
    public HttpResult modifyPatient(@RequestParam  Long patId,@RequestParam  String patName,@RequestParam String patPhone,@RequestParam String patIdentityNum) throws Exception {
        PubPatients patients = patientsService.selectByPrimaryKey(patId);
        patients.setPatName(patName);
        patients.setPatPhone(patPhone);
        patients.setPatIdentityNum(patIdentityNum);
        if (Optional.ofNullable(patients.getPatIdentityNum()).isPresent() && IdcardUtil.isValidCard(patients.getPatIdentityNum())){
            patients.setPatBirthday(LocalDateTimeUtil.of(IdcardUtil.getBirthDate(patients.getPatIdentityNum())));
            patients.setPatSex(IdcardUtil.getGenderByIdCard(patients.getPatIdentityNum()));
        }
        return HttpResult.success(patientsService.modifyPatient(patients));
    }


    @RequestMapping("/extractHisData")
    @ResponseBody
    public HttpResult extractHisData() throws Exception {
        patientsService.ExtractHisData();
        return HttpResult.success("抽取HIS患者信息成功！");
    }

}
